$.fn.pagination.defaults.displayMsg = '';
$(function(){
    obj.init();
});

var obj = new function(){
    'use strict';
    return {
        dataGrid: null,
        params: {
            schoolId: null,
            year: null,
            startTime: null,
            endTime: null,
            vague: null,
            className: null,
            userIds: null
        },
        init: function () {
            this.schDataGrid  = new xhDataGrid($('#schoolList'), 'cost/getSchools');
            this.dataGrid = new xhDataGrid($('#list'), 'Cost/getChargeDetail');

            this.schDataGrid.parseToolbar();
            $('#list_school_status').combobox('setValues', ['1', '2']);
            this.funObj().schoolSearch();
            this.dataGrid.parseToolbar().activeBtn($('#bt_list_del'));

            this.funObj().bindGridEvent();

            this.listener();
        },
        listener: function () {
            var $this = this;
            //学校搜索
            $('#bt_list_school_search').click(function(){
                $this.funObj().schoolSearch();
            });
            //搜索
            $('#bt_list_search').click(function(){
                $this.funObj().search();
            });
            //导入缴费信息文件
            $('#bt_list_import').click(function(){
                $this.funObj().importDetail();
            });
            //删除
            $('#bt_list_del').click(function () {
                if (xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().delDetail();
            });
            //一键拆分
            $('#bt_list_splitAll').click(function () {
                $this.funObj().splitAll();
            });
            //导出
            $('#bt_list_export').click(function () {
                $this.funObj().exportExcel();
            });
        },
        funObj: function(){
            var $this = this;
            return {
                bindGridEvent: function() {
                    $this.schDataGrid.onSelect = function (rowIndex, rowData) {
                        $this.params.schoolId = rowData.iSchoolId;
                        $this.funObj().search();
                        $this.dataGrid.setTitle(null, '-' + rowData.sSchoolName);
                    };
                    $this.schDataGrid.onLoadSuccess = function (data) {
                        if (data['rows'].length <= 0) {
                            return false;
                        }
                        $this.schDataGrid.command('selectRow', 0);
                        var p = $('#list').datagrid('getPager');
                        $(p).pagination({
                            displayMsg: '显示{from}到{to},共{total}记录',
                        });
                    };
                    xhExtra.clearLoadSuccess($this.dataGrid);
                },
                schoolSearch: function () {
                    $this.schDataGrid.reload({
                        vague: xhExtra.getValue($('#list_school_vague')),
                        status: xhExtra.getValue($('#list_school_status'))
                    });
                },
                search: function () {
                    $this.params.year = xhExtra.getValue($('#list_year'));
                    $this.params.vague = xhExtra.getValue($('#list_vague'));
                    $this.params.className = xhExtra.getValue($('#list_className'));
                    $this.params.startTime = xhExtra.getValue($('#list_startTime'));
                    $this.params.endTime = xhExtra.getValue($('#list_endTime'));
                    $this.dataGrid.reload($this.params);
                },
                importDetail: function () {
                    window.top.swal.setDefaults({
                        title: $this.schDataGrid.getSelectValue('sSchoolName'),
                        showCancelButton: true,
                        cancelButtonText: '取消',
                        showLoaderOnConfirm: true,
                        allowOutsideClick: false,
                        progressSteps: ['1', '2', '3']
                    });
                    var year,
                        serviceStart,
                        serviceEnd,
                        autoClass,
                        steps = [
                            {
                                html: '<input id="year" type="number" class="form-control" placeholder="缴费年度" style="margin-bottom: 10px;width: 50%;margin-left: 25%;"/>' +
                                    '输入服务时间：' +
                                    '<input id="serviceStart" type="date" class="form-control" placeholder="开始服务时间" style="margin-bottom: 10px;width: 50%;margin-left: 25%;" />' +
                                    '<input id="serviceEnd"  type="date" class="form-control" placeholder="结束服务时间" style="margin-bottom: 10px;width: 50%;margin-left: 25%;" />',
                                confirmButtonText: '下一步',
                                preConfirm: function() {
                                    return new Promise(function (resolve, reject) {
                                        year = $('#year', window.top.document).val();
                                        serviceStart = $('#serviceStart', window.top.document).val();
                                        serviceEnd = $('#serviceEnd', window.top.document).val();
                                        if (year < 2000 || year > 2100) {
                                            reject('缴费年份不正确！');
                                        } else {
                                            resolve();
                                        }
                                    })
                                }
                            },
                            {
                                text: '自动创建班级(新增学生)',
                                input: 'select',
                                inputOptions: {
                                    1: '行政班',
                                    // 2: '培优班'
                                },
                                confirmButtonText: '确认',
                                showCancelButton: false,
                                preConfirm: function(classType) {
                                    return new Promise(function (resolve, reject) {
                                        autoClass = classType;
                                        resolve();
                                    })
                                }
                            },
                            {
                                text: '导入excel文件',
                                input: 'file',
                                inputAttributes: {accept: '.xls,.xlsx'},
                                confirmButtonText: '导入',
                                preConfirm: function(file) {
                                    return new Promise(function (resolve, reject) {
                                        if (!file) {
                                            reject('文件不能为空！');
                                        } else {
                                            window.top.swal.resetDefaults();
                                            var fileData = new FormData();
                                            fileData.append('schoolId', $this.params.schoolId);
                                            fileData.append('year', year);
                                            fileData.append('file', file);
                                            fileData.append('autoClass', autoClass);
                                            fileData.append('serviceStart', serviceStart);
                                            fileData.append('serviceEnd', serviceEnd);
                                            $.ajax({
                                                url: baseUrl + 'Cost/importChargeDetail',
                                                type: 'POST',
                                                processData: false,
                                                contentType: false,
                                                data: fileData,
                                                complete: function (XMLHttpRequest) {
                                                    $this.funObj().dealImportResult(XMLHttpRequest.responseJSON);
                                                }
                                            });
                                        }
                                    })
                                }
                            }
                        ];
                    window.top.swal.queue(steps).then(function(result) {}, function(dismiss) {window.top.swal.resetDefaults();});
                },
                dealImportResult: function (result) {
                    if(xhExtra.checkError(result)) return false;
                    if (result.errorData.length > 0){
                        var content = '';
                        $.each(result.errorData, function(index, row){
                            // content += `<tr><td>${row.name}</td><td>${row.code}</td><td>${row.reason}</td></tr>`;
                            content += '<tr><td>' + row.name + '</td><td>' + row.code + '</td><td>' + row.reason + '</td></tr>';
                        });
                        window.top.swal({
                            title: result.msg,
                            type: 'warning',
                            confirmButtonText: '将以上学生转入该校并导入',
                            cancelButtonText: '关闭',
                            showLoaderOnConfirm: true,
                            showCancelButton: true,
                            allowOutsideClick: false,
                            html: '<table class="table table-striped"><tr>' +
                            '<th style="text-align: center">学生</th>' +
                            '<th style="text-align: center">缴费编号</th>' +
                            '<th style="text-align: center">原因</th>' +
                            '</tr>' + content + '</table>',
                            preConfirm: function() {
                                return new Promise(function (resolve, reject) {
                                    if (!$this.params.schoolId){
                                        reject('未知学校！');
                                    }
                                    xhExtra.ajaxRequest('Cost/transferStudent',
                                        {students: result.errorData, schoolId: $this.params.schoolId, year: $this.params.year},
                                        {success: true, table: $this.dataGrid}
                                    );
                                })
                            }
                        });
                    }
                    else{
                        window.top.xhTop.showSuccess(result.msg);
                    }
                    $this.dataGrid.reload();
                },
                delDetail: function () {
                    var ids = $this.dataGrid.getSelectValues('id');
                    if (ids.length <= 0) {
                        window.top.xhTop.showError('未选中记录');
                        return false;
                    }
                    xhExtra.askChangeStatus('cost/delChargeDetail', {ids: ids}, $this.dataGrid, '确认删除?');
                },
                splitAll: function () {
                    $this.params.iUserIds = $this.dataGrid.getSelectValues('iUserId');
                    window.top.swal({
                        title: '一键拆分',
                        html: '<input id="receivable" type="number" class="form-control" placeholder="应缴费用" style="margin-bottom: 10px;width: 50%;margin-left: 25%;"/>' +
                        '<input id="year" type="number" class="form-control" placeholder="年份" style="margin-bottom: 10px;width: 50%;margin-left: 25%;" />' +
                        '<input id="devPrice" type="number" class="form-control" placeholder="设备费" style="margin-bottom: 10px;width: 50%;margin-left: 25%;" />' +
                        '<input id="depositPrice" type="number" class="form-control" placeholder="押金" style="margin-bottom: 10px;width: 50%;margin-left: 25%;" />' +
                        '<input id="servicePrice" type="number" class="form-control" placeholder="服务费" style="margin-bottom: 10px;width: 50%;margin-left: 25%;" />' +
                        '<input id="tutorPrice" type="number" class="form-control" placeholder="辅导费" style="margin-bottom: 10px;width: 50%;margin-left: 25%;" />',
                        confirmButtonText: '拆分',
                        cancelButtonText: '取消',
                        showCancelButton: true,
                        preConfirm: function() {
                            return new Promise(function (resolve, reject) {
                                var params = {
                                    year: $('#year', window.top.document).val(),
                                    receivable: $('#receivable', window.top.document).val(),
                                    devPrice: $('#devPrice', window.top.document).val() ? $('#devPrice', window.top.document).val() : 0,
                                    depositPrice: $('#depositPrice', window.top.document).val() ? $('#depositPrice', window.top.document).val() : 0,
                                    servicePrice: $('#servicePrice', window.top.document).val() ? $('#servicePrice', window.top.document).val() : 0,
                                    tutorPrice: $('#tutorPrice', window.top.document).val() ? $('#tutorPrice', window.top.document).val() : 0
                                };
                                if (!params.year) {
                                    reject('年份不能为空');
                                } else if (!params.receivable) {
                                    reject('应缴不能为空');
                                } else {
                                    xhExtra.ajaxRequest(
                                        'cost/splitChargeBatch',
                                        $.extend({}, params, {schoolId: $this.params.schoolId, userIds: $this.params.iUserIds}),
                                        {check: true, success: true}
                                    );
                                    $this.dataGrid.reload();
                                }
                            })
                        }
                    })
                },
                exportExcel: function () {
                    $this.funObj().search();
                    location.href = baseUrl + 'cost/exportChargeDetail?' + xhTool.parseParam($this.params);
                }
            }
        }
    }
}
